package com.yjtravel.observer.eventbus;

import com.google.common.util.concurrent.MoreExecutors;

import java.util.List;
import java.util.concurrent.Executor;

/**
 * 阻塞同步的观察者模式
 * @author weiqi
 * @version 1.0
 * Create by 2024/7/11 9:27
 */
public class EventBus {

    private Executor executor;

    private ObserverRegistry registry = new ObserverRegistry();

    public EventBus(){
        //在当前线程中执行
        this(MoreExecutors.directExecutor());
    }

    public EventBus(Executor executor) {
        this.executor = executor;
    }

    public void registry(Object object){
        registry.registry(object);
    }

    public void post(Object event){
        List<ObserverAction> observerActions = registry.getMatchedObserverAction(event);
        for (ObserverAction observerAction : observerActions) {
            executor.execute(() -> observerAction.execute(event));
        }
    }
}
